package com.cao.coronavirustracker.controllers;


import com.cao.coronavirustracker.models.ReginStats;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;


import java.io.*;
import java.net.URI;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
@Controller
public class CoronavirusDataServise<records> {
    //爬取全球新型冠状病毒统计数据的csc文件
    @RequestMapping("/show")
    public String GetCOVID2019(Model model) {
        String CORNOA_VIRUS_DATA_URL = "https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";
        RequestEntity<Void> requestEntity = RequestEntity
                .get(URI.create(CORNOA_VIRUS_DATA_URL))
                .headers(httpHeaders -> httpHeaders.add("User-Agent", "Mozilla/5.0"))
                .build();
        ResponseEntity<Resource> exchange = new RestTemplate().exchange(requestEntity, Resource.class);
        Resource body = exchange.getBody();
        Iterable<CSVRecord> records = null;
        ArrayList<ReginStats> list = new ArrayList<ReginStats>();
        try {
            InputStream in = body.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
             records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(reader);
        } catch (IOException e) {
            System.out.println("Error" + e);
        }
        for (CSVRecord record : records) {
            String state = record.get("Province/State");
            String country = record.get("Province/State");
            String lasttotalnumber = record.get(record.size() - 1);
            String lasttotalnumber2 = record.get(record.size() - 2);
            Integer intdiffFromprevDay = Integer.parseInt(lasttotalnumber) - Integer.parseInt(lasttotalnumber2);
            String diffFromprevDay = String.valueOf(intdiffFromprevDay);
            ReginStats reginStats = new ReginStats();
            reginStats.setState(state);
            reginStats.setCountry(country);
            reginStats.setDiffFromprevDay(lasttotalnumber);
            reginStats.setLasttotalnumber(diffFromprevDay);
            list.add(reginStats);
        }
        model.addAttribute("list",list);
        return "index";
    }

}
